package org.example.task.controller;


import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.task.converter.RoleConverterMapper;
import org.example.task.model.dto.role.AssignRole;
import org.example.task.model.dto.role.CreateRole;
import org.example.task.model.po.Role;
import org.example.task.model.vo.R;
import org.example.task.model.vo.role.RoleVO;
import org.example.task.service.IRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色接口
 *
 * @module 角色接口
 */
@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
public class RoleController {
    private final IRoleService roleService;
    private final RoleConverterMapper roleConverterMapper;

    /**
     * 创建角色
     *
     * @param createRole 新角色数据
     * @return 结果
     */
    @PreAuthorize("hasAuthority('role_create')")
    @PostMapping("/create")
    public R addRole(@Valid @RequestBody CreateRole createRole) {
        boolean flag = roleService.addRole(createRole);
        if (flag) {
            return R.success();
        }
        return R.error("新增失败");
    }

    /**
     * 分配角色
     *
     * @param assignRole 分配数据
     * @return 结果
     */
    @PreAuthorize("hasAuthority('role_edit')")
    @PutMapping
    public R assignRole(@Valid @RequestBody AssignRole assignRole) {
        boolean flag = roleService.assignRole(assignRole);
        if (flag) {
            return R.success();
        }
        return R.error("分配失败");
    }

    /**
     * 获取角色列表
     *
     * @return 角色数据
     */
    @PreAuthorize("hasAuthority('role_list')")
    @GetMapping
    public R<List<RoleVO>> getRoleList() {
        List<Role> roleList = roleService.list();
        List<RoleVO> roleVOS = roleConverterMapper.rolesToRoleVOs(roleList);
        return R.success(roleVOS);
    }
}
